package com.neusoft.NEPS.common;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FileUtils {
    public static <K,V>void writeMapObject(String fileName, Map<K,V> map) throws IOException {
        File file = new File(fileName);
        if(!file.exists()){
            file.createNewFile();
        }
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(map);
            oos.flush();
        } catch (IOException e) {
            System.out.println("写入数据失败！");
            e.printStackTrace();
        }
    }
    public static <K, V> Map<K, V> readMapObject(String fileName) {
        File file = new File(fileName);
        // 如果文件不存在或为空，直接返回一个空的 HashMap
        if (!file.exists() || file.length() == 0) {
            return new HashMap<>();
        }
        try (FileInputStream fis = new FileInputStream(file);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            return (Map<K, V>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("从文件读取Map失败！");
            e.printStackTrace();
            return new HashMap<>();
        }
    }
}
